<template>
  <div class="InboundList-box">
    <!-- 政策文件 -->
    <h3 class="mb16">政策文件</h3>
    <!-- 搜索栏 -->
    <serchForm :Form="inventoryForm" :FormLabel="inventoryFormLabel" @onSearch="onSearch" />
    <!-- 增删改查 -->
        <div class="function-box" v-if="checkPermi(['system:notice:edit'])">
                <el-button class="createBtn" @click="handleAdd">发布</el-button>
                <!-- <el-button class="createBtn">编辑</el-button> -->
                <!-- <el-button class="exportBtn">删除</el-button> -->
        </div>
    <!-- 政策文件列表页面 -->
    <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column label="标题名称"  align="left" prop="noticeTitle" :show-overflow-tooltip="true"/>
      <el-table-column label="发布人" align="center" prop="nickName" width="160"/>
      <el-table-column label="发布时间" sortable align="center" prop="releaseDate" width="200" >
         <template #default="scope">
             <!-- {{ scope.row.releaseDate.slice(0, 16) }} -->
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="200">
        <template #default="scope">
          <el-button  link class="putBtn" @click="handleDetail(scope.row)">详情</el-button>
          <el-button link class="putBtn" @click="handleClick(scope.row)" v-if="checkPermi(['system:notice:edit'])" >
            编辑
          </el-button>
          <el-button link class="delBtn" @click="handleDelete(scope.row)" v-if="checkPermi(['system:notice:edit'])" >删除</el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="pageNum" v-model:limit="pageSize"
      @update:page="updatePage" @update:limit="updateLimit" :pageSizes="pageSizes" @pagination="handleChange" />

      <!-- 添加或修改公告对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="780px">
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="10" style="margin-right: 26px;">
            <el-form-item label="标题名称" prop="noticeTitle">
              <el-input v-model="form.noticeTitle" placeholder="请输入标题名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布范围" prop="releaseScope">
              <!-- 发布范围 -->
              <el-tree-select
                ref="treeRef"
                v-model="form.releaseScope"
                :data="genderOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                check-strictly
                placeholder="请选择发布范围"
                value-key="id"
                multiple
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容">
              <editor v-model="form.noticeContent" :min-height="192" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="createBtn3" @click="cancel">重置</el-button>
          <el-button class="createBtn" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import serchForm from '@/components/inventory/serchForm.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import pagination from '@/components/Pagination/index'
import { checkPermi } from '@/utils/permission.js'
import {listNotice,getdeptApi,addNotice,delNotice,updateNotice} from '@/api/system/notice.js'
import {useListStore} from "@/store/modules/news";
import {storeToRefs} from "pinia";
const newsPut = useListStore()
const { editIdLong } = storeToRefs(newsPut) // 解构并保持响应性
const router = useRouter();
const route = useRoute();
const data = reactive({});
const { proxy } = getCurrentInstance();

const loading = ref(false)
const treeRef = ref(null);
// 表单
let inventoryForm = ref({
  releaseDate: '', // 发布日期
  noticeTitle: '', // 标题名称
})
// 表单数据标题
let inventoryFormLabel = ref([
  {
    name: 'releaseDate',
    label: '发布日期',
    type: 'datetimerange',
  },
  {
    name: 'noticeTitle',
    label: '标题名称',
  },
])
// 查询
const onSearch = (v) => {
  console.log(v, '查询入库参数')
  // 每次查询后回到页1
  pageNum.value = 1
  v.startDate = v.releaseDate[0]
  v.endDate = v.releaseDate[1]
  listNoticeFn(v)
}

const open = ref(false);
const title = ref("");

const pageSizes = ref([10, 20, 30, 50])
// 总条目数   pageSize 加 1
let total = ref(0)
// 当前页数
let pageNum = ref(1)
// 条数
let pageSize = ref(50)

// 当前页面位置发生变化
const updatePage = (val) => {
  console.log(val, '第几页');
  pageNum.value = val
  listNoticeFn()
}
// 条目个数发生变化
const updateLimit = (val) => {
  console.log(val, '每页多少条');
  pageSize.value = val
  listNoticeFn()
}
// 分页器大小  当前分页器
const handleChange = (page, pageSize) => {
    console.log(page,pageSize,'打印page,pageSize');
    
}
// 表格数据内容
let dataList = ref([])
const form = ref({
    noticeTitle: '',
    noticeType: 3,
    noticeContent:'',
    releaseScope:[],
  })
/** 表单重置 */
function reset() {
  form.value = {
    noticeTitle:'',
    noticeContent:undefined,
    releaseScope:[],
    noticeType: 3,
  }
  proxy.resetForm('noticeRef')
}
/** 新增按钮操作 */
// function handleAdd() {
//   reset()
//   open.value = true
//   title.value = '上传政策文件'
//   editId.value = -1
// }
const rules =ref({
    noticeTitle: [{ required: true, message: "标题名称不能为空", trigger: "blur" }],
    releaseScope: [{ required: true,message: '请选择发布范围',trigger: 'change', }],
  })

const editId = ref(-1)
/** 修改按钮操作 */
function handleClick(row) {
  console.log(row,'编辑数据');
  editId.value = row.noticeId
  open.value = true;
  title.value = "编辑政策文件";
  form.value.noticeTitle = row.noticeTitle
  form.value.noticeContent = row.noticeContent
  form.value.releaseScope = JSON.parse(row.releaseScope)
}

const pageType = ref('') // 当前页面状态
/** 新增按钮操作 */
function handleAdd() {
  title.value = '上传政策文件'
  newsPut.fetchList({noticeId:-1})
  pageType.value = 'policyadd'
  router.push({path:`/newsDetail/${pageType.value}/${editIdLong.value}`})
  // router.push({path:`/newsDetail/${editIdLong.value}`})
}

// /** 修改按钮操作 */
// function handleClick(row) {
//   title.value = "编辑政策文件";
//   newsPut.fetchList(row)
//   pageType.value = 'policyedit'
//   router.push({path:`/newsDetail/${pageType.value}/${editIdLong.value}`})
//   // router.push({path:`/newsDetail/${editIdLong.value}`})
// }
/** 详情按钮 */
function handleDetail(row) {
  newsPut.fetchList(row)
  router.push({
    path: `/newsDetailYulan`,
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs['noticeRef'].validate((valid) => {
    if (valid) {
      if (editId.value===-1) {
        //  form.value.releaseScope = form.value.releaseScope.join(',')
          form.value.releaseScope = JSON.stringify(form.value.releaseScope)
          addNotice(form.value).then(res=>{
          if(res.code===200){
              ElMessage({
                 message: '添加成功',
                 type: 'success',
               })
               open.value = false
               listNoticeFn()
          }
     })
      } else {
         form.value.releaseScope = JSON.stringify(form.value.releaseScope)
         form.value.noticeId = editId.value
          updateNotice(form.value).then(res=>{
              if(res.code===200){
                  ElMessage({
                 message: '编辑成功',
                 type: 'success',
               })
               open.value = false
               listNoticeFn()
              }
          })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
    ElMessageBox.confirm(
    '确定要删除该政策文件吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
         delNotice(row.noticeId).then(res=>{
            console.log(res,'删除成功');
            if(res.code===200){
                ElMessage({
                 message: '删除成功',
                 type: 'success',
               })
               listNoticeFn()
            }
         })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}
/** 取消按钮 */
function cancel() {
  // open.value = false
  reset()
}
const listNoticeFn = (data='')=>{  //获取列表数据
  let page = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    noticeType:3
  }
  let params = Object.assign(page,data)
  delete params.releaseDate
  console.log(params,'打印params');
    listNotice(params).then(res=>{
       console.log(res,'列表数据');
       if(res.code===200){
            dataList.value = res.rows
            total.value = res.total
       }
    })
}
// 获取发布范围下拉信息
const genderOptions = ref([])
const getdeptApiFn = async () => {
  let page = {
     pageNum: 1,
     pageSize:-1,
  }
  let res = await getdeptApi(page)
  console.log(res,'打印发布范围');
  if (res.code == 200) {
     genderOptions.value = res.data
  }
}
onMounted(() => {
  Promise.all([listNoticeFn(),getdeptApiFn()])
})
</script>

<style lang='scss' scoped>
.InboundList-box {
  padding: 16px;

  .function-box {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
  }
}
.dialog-footer {
  display: flex;
  justify-content: center; /* 水平居中 */
}
</style>
